<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="78px">
      <el-form-item label="课程号" prop="courseNumber">
        <el-input v-model="queryParams.courseNumber" placeholder="请输入课程号" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="费用名称" prop="costname">
        <el-input v-model="queryParams.costname" placeholder="请输入费用名称" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['village:expenditure:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['village:expenditure:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['village:expenditure:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['village:expenditure:export']"
        >导出
        </el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="inputExport"
                   v-hasPermi="['village:expenditure:export']"
        >导入
        </el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="DownloadTemplate"
                   v-hasPermi="['village:expenditure:export']"
        >下载导入模板
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="课程号" align="center" prop="courseNumber"/>
      <el-table-column label="教改项目" align="center" prop="villageEducationalReformName"/>
      <el-table-column label="课题级别" align="center" prop="rank">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.village_expenditure_grade" :value="scope.row.rank"/>
        </template>
      </el-table-column>
      <el-table-column label="经费基准" align="center" prop="expenditure"/>
      <el-table-column label="费用名称" align="center" prop="costname"/>
      <el-table-column label="报销金额" align="center" prop="reportForDeletion"/>
      <el-table-column label="剩余经费" align="center" prop="surplusFunds"/>
      <el-table-column label="报销人" align="center" prop="reportForDeletionName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-s-unfold" @click="selectdetailopen(scope.row)">详情
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['village:expenditure:edit']"
          >修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['village:expenditure:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />

    <!-- 添加或修改教改项目结课对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" :inline="true">

        <el-form-item label="教改项目" prop="villageEducationalReformId">
          <el-select
            @change="xialaxuanxaing"
            v-loadMore="loadMore"
            style="width: 198px" v-model="form.villageEducationalReformId" remote
            :remote-method="remoteMethod" filterable placeholder="请选择"
          >
            <el-option v-for="dict in optionsitem" :key="dict.value" :label="dict.label" :value="parseFloat(dict.value)">
              <span style="float: left">{{ dict.label }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="课程号" prop="courseNumber">
          <el-input v-model="form.courseNumber" placeholder="请输入课程号"/>
        </el-form-item>
        <el-form-item label="课题级别" prop="rank">
          <el-select style="width: 198px" v-model="form.rank" placeholder="请选择课题级别">
            <el-option v-for="dict in dict.type.village_expenditure_grade" :key="dict.value" :label="dict.label"
                       :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经费基准" prop="expenditure">
          <el-input v-model="form.expenditure" placeholder="请输入经费基准" disabled/>
        </el-form-item>


        <el-form-item style="width: 340px" label="费用名称" prop="costname">
          <el-autocomplete
            style="width: 198px"
            class="inline-input"
            v-model="form.costname"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>


        <el-form-item label="报销金额" prop="reportForDeletion">
          <el-input v-model="form.reportForDeletion" placeholder="请输入报销金额"/>
        </el-form-item>
        <el-form-item label="任务书预算" prop="missionBookBudget">
          <el-input style="width: 198px" v-model="form.missionBookBudget" placeholder="请输入任务书预算"/>
        </el-form-item>
        <el-form-item label="剩余经费" prop="surplusFunds">
          <el-input v-model="form.surplusFunds" placeholder="请输入剩余经费" disabled/>
        </el-form-item>
        <el-form-item label="报销人" prop="reportForDeletionName" style="width: 500px">
          <el-input style="width: 198px" v-model="form.reportForDeletionName" placeholder="请输入报销人"/>
        </el-form-item>
        <el-form-item label="经济业务简述" prop="economicWork">
          <el-input v-model="form.economicWork" type="textarea" placeholder="请输入内容" style="width: 520px;"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" style="width: 520px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="导入文件" :visible.sync="exportopen" width="500px" append-to-body>

      <el-upload class="upload-demo" ref="upload" :action="uploadFileUrl" :headers="headers" :on-success="successexport"
                 :before-upload="handleBeforeUpload" :on-error="handleUploadError" :auto-upload="false"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <!--        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
        <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件，且不超过200M</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitUpload">确 定</el-button>

      </div>

    </el-dialog>

    <el-dialog title="详细信息" :visible.sync="detailopen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" inline>
        <el-form-item label="教改项目：" style="width: 700px">
          {{ form.villageEducationalReformName }}
        </el-form-item>
        <el-form-item label="课程号：" style="width: 300px">
          {{ form.courseNumber }}
        </el-form-item>
        <el-form-item label="课题级别：" >
          {{ form.rank }}
        </el-form-item>
        <el-form-item label="经费基准：" style="width: 300px">
          {{ form.rank }}
        </el-form-item>
        <el-form-item label="费用名称：" style="width: 300px">
          {{ form.costname }}
        </el-form-item>

        <el-form-item label="报销金额：" style="width: 300px">
          {{ form.reportForDeletion }}
        </el-form-item>
        <el-form-item label="剩余经费：" style="width: 300px">
          {{ form.surplusFunds }}
        </el-form-item>
        <el-form-item label="任务书预算：" style="width: 300px">
          {{ form.missionBookBudget }}
        </el-form-item>
        <el-form-item label="报销人：">
          {{ form.reportForDeletionName }}
        </el-form-item>
        <el-form-item label="经济业务简述：" style="white-space: normal; word-break: break-word;">
          <div style="width: 500px;">
          {{ form.economicWork }}
          </div>
        </el-form-item>
        <el-form-item label="备注：" style="white-space: normal; word-break: break-word;">

          <div style="width: 500px;">
            {{ form.remark }}
          </div>

        </el-form-item>
      </el-form>

    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import infiniteScroll from 'vue-infinite-scroll'

Vue.use(infiniteScroll)

import {
  listDetail,
  nolistDetail,
  getDetail,
  delDetail,
  addDetail,
  updateDetail,
  inputDetail
} from '@/api/village/detail'
import { listReform, getReform } from '@/api/village/reform'
import { getToken } from '@/utils/auth'
import { noListManage } from '@/api/village/manage'

export default {
  name: 'Detail',
  dicts: ['village_expenditure_grade'],
  data() {
    return {
      BAOXIAOJINECHUSHI:0,
      SHENFYUJINE:0,
      isadd:true,
      zizhuchu:0,
      datt: 0,
      price: 0,
      pageData: {
        pageNum: 1,
        pageSize: 10
      },
      pagetotal: 0,
      loadingMore: false,
      allItems: [],
      restaurants: [],

      expenselist: [],
      options: [],
      optionsitem: [],
      value: [],
      list: [],
      loadings: false,
      states: [],
      detailopen: false,
      fileType: ['xls', 'xlsx'],
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/village/detail/input',
      exportopen: false,
      reformList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教改项目结课表格数据
      detailList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseNumber: null,
        rank: null,
        expenditure: null,
        costname: null
      },
      // 表单参数
      form: {
        reportForDeletion:0
      },
      // 表单校验
      rules: {
        villageEducationalReformId: [
          { required: true, message: '教改项目不能为空', trigger: 'blur' }
        ],
        expenditure: [
          { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的数字', trigger: ['blur'] }
        ],
        missionBookBudget: [
          { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的数字', trigger: ['blur'] }
        ],

        courseNumber: [
          { required: true, message: '课程号不能为空', trigger: 'blur' }
        ],
        rank: [
          { required: true, message: '课题级别不能为空', trigger: 'blur' }
        ],
        costname: [
          { required: true, message: '费用名称不能为空', trigger: 'change' }
        ],
        reportForDeletion: [
          { required: true, message: '费用名称不能为空', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let zhi = 0
              let isno = 0
              let zongzhi = 0
              let issout=0
             if(this.isadd){
               zhi = parseFloat(this.form.expenditure)
               let baoxiao = isNaN(this.form.reportForDeletion) ? 0 : parseFloat(this.form.reportForDeletion)
               zongzhi = baoxiao + parseFloat(this.price)
               isno = parseFloat(zhi) - (parseFloat(baoxiao) + parseFloat(this.price))
               this.form.surplusFunds = isNaN(isno)?this.SHENFYUJINE:isno

               issout = parseFloat(this.form.expenditure)-parseFloat(this.price)
             }else {

               zhi = this.form.expenditure

               let rf = isNaN(this.form.reportForDeletion)?0:this.form.reportForDeletion

               isno = parseFloat(zhi) - this.zizhuchu - parseFloat(rf) + parseFloat(this.BAOXIAOJINECHUSHI)

               this.form.surplusFunds = isNaN(isno)?parseFloat(zhi) - this.zizhuchu + parseFloat(this.BAOXIAOJINECHUSHI):isno
               console.log('this.BAOXIAOJINECHUSHI',this.BAOXIAOJINECHUSHI)
               console.log('rf',rf)
               zongzhi = parseFloat(rf) + this.zizhuchu - parseFloat(this.BAOXIAOJINECHUSHI)
               console.log('this.zizhuchu',this.zizhuchu)
               issout = parseFloat(this.form.expenditure) -this.zizhuchu +parseFloat(this.BAOXIAOJINECHUSHI)
             }

              console.log('zongzhi',zongzhi)
              console.log('this.form.expenditure',this.form.expenditure)
              if (zongzhi > parseFloat(this.form.expenditure)) {

                  callback(new Error(`报销金额不能超过${issout}元`))

              } else {
                callback() // 验证通过
              }
            },

            trigger: ['blur']
          }
        ],
        reportForDeletionName: [
          { required: true, message: '报销人不能为空', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.getList()
    this.getpedagogicalList()
  },
  mounted() {
    this.list = this.states.map(item => {
      return { value: `${item}`, label: `${item}` }
    })
    this.restaurants = this.loadAll()
  },
  methods: {

    xialaxuanxaing(sun) {
      getReform(sun).then(response => {
        this.form.expenditure = response.data.projectFund
        this.datt = response.data.projectFund
        nolistDetail({ villageEducationalReformId: sun }).then(response => {
          this.price = 0
          response.rows.map((item) => {
            this.price = parseFloat(this.price) + parseFloat(item.reportForDeletion)
          })
          console.log(parseFloat(this.datt))
          console.log(parseFloat(this.price))
          this.form.surplusFunds = 0
          this.form.surplusFunds = parseFloat(this.datt) - parseFloat(this.price)
          console.log(this.form.surplusFunds)
          this.SHENFYUJINE=this.form.surplusFunds
        })

        nolistDetail({
          villageEducationalReformId:response.data.id
        }).then(response => {
          // this.price = 0
          console.log(response.rows)
          response.rows.map((item) => {
            this.zizhuchu = parseFloat(this.price) + parseFloat(item.reportForDeletion)
          })
        })
      })
    },
    loadMore() {
      this.pageData.pageNum++

      if (this.list.length !== this.pagetotal) {
        listReform(this.pageData).then(response => {
          this.reformList = response.rows
          this.pagetotal = response.total
          this.options = this.reformList.map(r => {
            return {
              label: r.location,
              value: r.id
            }
          })
          this.states = this.options.map(item => item.label)
          this.options.forEach(option => {
            this.list.push(option)
          })

        })
      }

      // this.sceneData(this.pageData);
    },
    querySearch(queryString, cb) {

      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)

    },
    createFilter(queryString) {

      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    loadAll() {

      return this.expenselist

    },
    handleSelect(item) {
      this.form.missionBookBudget = item.address
    },
    addScrollListener() {
      this.$nextTick(() => {
        const suggestionBox = document.querySelector('.el-autocomplete-suggestion__wrap')
        if (suggestionBox) {
          suggestionBox.addEventListener('scroll', this.handleScroll)
        }
      })
    },
    handleScroll(event) {
      const el = event.target
      if (el.scrollHeight - el.scrollTop === el.clientHeight && !this.loadingMore) {
        this.loadMoreData()
      }
    },
    loadMoreData() {
      this.loadingMore = true
      this.queryParams.pageNum += 1
      listDetail(this.queryParams).then(response => {
        if (response && response.rows && Array.isArray(response.rows)) {
          response.rows.forEach(item => {
            if (!this.allItems.some(existingItem => existingItem.value === item.costname)) {
              this.allItems.push({ 'value': item.costname })
            }
          })
        }
        this.loadingMore = false
      }).catch(() => {
        this.loadingMore = false
      })
    },

    remoteMethod(query) {

      if (query !== '') {
        this.loadings = true // 注意这里是 this.loadings
        this.optionsitem = []

        listReform({ location: query }).then(response => {
          this.reformList = response.rows
          this.optionsitem = this.reformList.map(r => {
            return {
              label: r.location,
              value: r.id
            }
          })
        })

        this.loadings = false
      } else {
        this.optionsitem = this.list
      }
    },
    selectdetailopen(row) {
      getDetail(row.id).then(response => {
        this.form = response.data
        this.form.villageEducationalReformId = response.data.villageEducationalReformId // 确保设置默认值
        this.detailopen = true
      })
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError('导入失败，请重试')
      this.$modal.closeLoading()
    },
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.')
        const fileExt = fileName[fileName.length - 1]
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join('/')}格式文件!`)
          return false
        }
      }
      return true
    },
    submitUpload() {
      this.$refs.upload.submit()

    },
    successexport(response, file, fileList) {
      if (response.code === 200) {
        this.exportopen = false
        this.$modal.msgSuccess('导入成功')
        this.$refs['upload'].clearFiles()
        this.getList()
      } else {
        this.exportopen = false
        this.$refs['upload'].clearFiles()
        // 后端返回了成功状态码以外的其他情况，按失败处理
        this.$modal.msgError(response.message || '文件上传失败')
      }

    },
    inputExport() {
      this.exportopen = true
    },
    getpedagogicalList() {
      this.loadings = true
      listReform({}).then(response => {
        this.reformList = response.rows
        this.options = this.reformList.map(r => {
          return {
            label: r.location,
            value: r.id
          }
        })
        this.states = this.options.map(item => item.label)
        this.list = this.options
        this.optionsitem = this.options
        // this.list = this.states.map(label => {
        //   return { value: label, label: label }
        // })
        // console.log(this.list)
        this.loadings = false
      })
    },
    /** 查询教改项目结课列表 */
    getList() {
      this.loading = true
      listDetail(this.queryParams).then(response => {
        this.detailList = response.rows
        this.total = response.total
        this.loading = false
      })
      noListManage({}).then(response => {

        this.expenselist = response.rows.map(item => ({
          address: item.money,

          value: item.name
        }))
        this.restaurants = this.loadAll()
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        villageEducationalReformId: null,
        courseNumber: null,
        rank: null,
        expenditure: null,
        costname: null,
        economicWork: null,
        reportForDeletion: null,
        surplusFunds: null,
        missionBookBudget: null,
        reportForDeletionName: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        isDelete: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.isadd = true
      this.open = true
      this.title = '添加记账支出'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDetail(id).then(response => {
        this.form = response.data
        this.BAOXIAOJINECHUSHI = response.data.reportForDeletion
        this.open = true
        this.title = '修改记账支出'

        console.log(response.data)
        nolistDetail({
          villageEducationalReformId:response.data.villageEducationalReformId
        }).then(response => {
          this.zizhuchu = 0
          console.log(response.rows)
          response.rows.map((item) => {
            this.zizhuchu = parseFloat(this.zizhuchu) + parseFloat(item.reportForDeletion)
          })
          // console.log('xxxxxx',this.zizhuchu)
        })
      })
      this.isadd = false
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {

        if (valid) {
          if (this.form.id != null) {
            updateDetail(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()

            })
          } else {
            addDetail(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除当前记账支出数据项？').then(function() {
        return delDetail(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('village/detail/export', {
        ...this.queryParams
      }, `detail_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板 */
    DownloadTemplate() {
      this.download('village/detail/exportfile', {
        ...this.queryParams
      }, `导入模板.xlsx`)
    },
    skipDetail(row) {
      this.$router.push(`/expendituredetail?id=${row.id}`)
    }
  }
}
</script>

<style scoped>
.el-input.is-disabled /deep/ .el-input__inner {
  color: #000000;
}
</style>
